import { Act_type, IAct, IState, ITodo } from "../../../types";

const reducer = (state: IState, actions: IAct): IState => {
  const { type, payload } = actions;
  switch (type) {
    case Act_type.ADD_TODO:
      return {
        ...state,
        todoList: [...state.todoList, payload as ITodo]
      };
    case Act_type.REMOVE_TODO:
      return {
        ...state,
        todoList: state.todoList.filter(v => v.id !== payload)
      };
    case Act_type.TOGGLE_TODO:
      return {
        ...state,
        todoList: state.todoList.map(v => {
          if (v.id === payload) {
            return {
              ...v,
              completed: !v.completed
            };
          }
          return v;
        })
      };
    case Act_type.INIT_DATA:
      return {
        ...state,
        todoList: payload as ITodo[]
      };
    default:
      return state;
  }
};
export default reducer;
